-- 导入响应式api
local r = require "ch8.r"

local reactive = r.reactive
local ref      = r.ref
local effect   = r.effect
local dump     = r.dump
-- print("rApi", reactive, ref, effect)


local function createRenderer(...)
    local createElement, insert, setElementText = ...
    -- print("options", createElement, insert, setElementText)
    -- @type fun(n1,n2,container)
    local patch;

    local function mountElement(vnode, container)
        -- type
        local el = createElement(vnode["type"])
        -- children
        if (type(vnode.children) == "string") then
            setElementText(el, vnode["children"])
        elseif (type(vnode.children) == "table") then
            -- children子节点
            for i = 1, #vnode.children, 1 do
                patch(null, vnode.children[i], el)
            end
        end
        -- props
        if (type(vnode.props) == "table") then
            for key, value in pairs(vnode.props) do
                el.setAttribute(key, value)
            end
        end
        -- parent
        insert(el, container)
    end

    patch = function(n1, n2, container)
        if (not n1) then
            mountElement(n2, container)
        else

        end
    end

    local function render(vnode, container)
        if (vnode) then
            -- 挂载新的 比较
            patch(container._vnode, vnode, container)
        else
            -- 卸载旧的
            if (container._vnode) then
                container["content"] = ""
            end
        end
        -- 记录旧的
        container._vnode = vnode
        print("container", container._vnode)
    end

    return {
        render = render
    }
end

local renderer = createRenderer(
-- createElement
    function(tag)
        print(tag, "createElement")
        local tagEl = {}
        tagEl["tag"] = tag;
        tagEl["attr"] = {}
        tagEl["setAttribute"] = function(key, value)
            print("setAttribute", key, value)
            tagEl["attr"][key] = value
        end
        return tagEl
    end,
    -- insert
    function(el, parent)
        dump({ parent, el }, "insert")
        parent["children"] = el
    end,
    -- setElementText
    function(el, text)
        dump({ el, text }, "set text")
        el["text"] = text
    end
);

-- print("render",renderer.render)

local container = { type = "root" }
local vnode = {
    type = 'button',
    props = {
      disabled =  ''
    },
    children = 'Button'
  }

renderer.render(vnode, container)
